package com.my.app.tools.core.service.ocr;

import com.google.common.collect.Lists;
import com.my.app.tools.pojo.em.client.OcrClientBaiDu;
import com.my.app.tools.pojo.vo.GlobalResponseEntity;
import com.my.app.tools.util.LogUtil;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

public class OcrBaiduBasicService implements IOcrApiService {

    /**
     * ocr文字识别（通用基础）
     *
     * @param imgData
     * @return
     * @author guochaohui
     * @date 2020-04-03 16:30
     */
    @Override
    public GlobalResponseEntity<List<String>> imageOcr(byte[] imgData) {
        try {
            // 传入可选参数调用接口
            HashMap<String, String> options = new HashMap<String, String>();
            options.put("language_type", "CHN_ENG");
            options.put("detect_direction", "true");
            options.put("probability", "true");

            JSONObject jsonObject = OcrClientBaiDu.INSTANCE.getClient().basicGeneral(imgData, options);
            LogUtil.info("ocr baidu basic result: " + jsonObject.toString());
            if (jsonObject.has("error_msg")) {
                String errorMsg = jsonObject.getString("error_msg");
                String errorCode = jsonObject.getString("error_code");
                String errorMessage = errorMsg + "." + errorCode;
                LogUtil.error("ocr baidu basic fail: " + errorMessage);
                return GlobalResponseEntity.failure("识别失败.请确认接口配置参数是否正确.或稍后再试." + errorMessage);
            }
            JSONArray words = jsonObject.getJSONArray("words_result");
            List<String> results = Lists.newArrayList();
            for (int i = 0; i < words.length(); i++) {
                JSONObject word = words.getJSONObject(i);
                results.add(word.getString("words"));
            }
            return GlobalResponseEntity.success("识别成功", results);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.error("ocr baidu basic error: " + e.getMessage());
            return GlobalResponseEntity.failure(e.getMessage());
        }
    }

}